package blogwork;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

public class DBUtils {
	
	private static final String JDBC_URL = "jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf8&useSSL=true";
	private static final String DB_USER = "root";
	private static final String DB_PWD = "shihuang";
	
	/**
	 * 获取数据库连接
	 * @return
	 */
	public static Connection getConnection(){
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		Connection conn = null;
		
		try {
			conn =  DriverManager.getConnection(JDBC_URL, DB_USER, DB_PWD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 查询语句工具类
	 * @param tableName
	 * @param columns
	 * @param whereSql
	 * @return
	 */
	public static String getSelectSQL(String tableName,List<String> columns,String whereSql){
		
		String selectSQL = "select ";
		if( null == columns ){
			selectSQL +="*,";
		}else{
			for (String column : columns) {
				selectSQL +=column + ",";
			}
		}
		selectSQL = selectSQL.substring(0,selectSQL.length()-1);
		
		selectSQL +=" from "+tableName;
		if( null!=whereSql && !whereSql.isEmpty() ){
			selectSQL +=" where "+whereSql;
		}
		
		return selectSQL;
	}
	
}
